import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { useNavigate } from 'react-router-dom';
import cookie from "react-cookies";
import { getCodeImg, login } from "../../api/login";
import Card from '@material-ui/core/Card';
import { setToken, getToken } from "../../uitl/auth";
import { createBrowserHistory } from "history";
import bgImg from '../../image/bg.jpg'




function Copyright() {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {'Copyright © '}
            <Link color="inherit" href="https://material-ui.com/">
                Your Website
            </Link>{' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}

const useStyles = makeStyles((theme) => ({
    root: {
        width: '1910px',
        height: '900px',
        backgroundImage: `url(${bgImg})`,
        paddingTop: '120px'
    },
    card: {
        maxWidth: 600,
        margin: '0 auto',
    },
    paper: {
        marginTop: theme.spacing(8),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',

    },
    avatar: {
        margin: theme.spacing(1),
        backgroundColor: theme.palette.secondary.main,
    },
    form: {
        width: '100%', // Fix IE 11 issue.
        marginTop: theme.spacing(1),
    },
    submit: {
        margin: theme.spacing(3, 0, 2),
    },
}));

export default function SignIn() {
    const classes = useStyles();

    let navigate = useNavigate();
    // const handleClickLogin = () => {
    //     navigate('/');
    // };
    // const handleClickRegister = () => {
    //     navigate('/register');
    // };


    const getCode = () => {
        getCodeImg().then((res) => {
            // console.log("1", res)
            const newUrl = "data:image/gif;base64," + res.img
            let newData = { ...data }
            newData.loginForm.uuid = res.uuid;
            setData({ ...data });
            setUrl(newUrl);
        });
    };




    const handleLogin = () => {
        if (data.loginForm.rememberMe) {
            cookie.save("username", data.loginForm.username);
            cookie.save("password", data.loginForm.password);
            cookie.save("rememberMe", data.loginForm.rememberMe);
        } else {
            cookie.remove("username");
            cookie.remove("password");
            cookie.remove("rememberMe");
        }
        login(
            data.loginForm.username,
            data.loginForm.password,
            data.loginForm.code,
            data.loginForm.uuid
        )
            .then((res) => {
                console.log('123')
                console.log(res)
                setToken(res.token);
                let history = createBrowserHistory();
                history.push({
                    pathname: "/",
                });
                history.go();
            })
            .catch((error) => {
                console.log('登录失败')
                getCodeImg().then((res) => {
                    console.log("err", res)
                    data.codeUrl = "data:image/gif;base64," + res.img;
                    data.loginForm.uuid = res.uuid;
                    setUrl(...data.codeUrl);

                });
                setsnackbar({
                    open: true,
                    text: error.message,
                });
            });

    };
    const [url, setUrl] = React.useState("");
    const [data, setData] = React.useState({
        codeUrl: "",
        cookiePassword: "",
        loginForm: {
            username: "admin",
            password: "admin123",
            rememberMe: false,
            code: "",
            uuid: "",
        },
        loginRules: {
            username: [
                { required: true, trigger: "blur", message: "用户名不能为空" },
            ],
            password: [{ required: true, trigger: "blur", message: "密码不能为空" }],
            code: [{ required: true, trigger: "change", message: "验证码不能为空" }],
        },
        loading: false,
        redirect: undefined,
    });
    const changeForm = (mes) => {
        const newLoginForm = data.loginForm;
        return (event) => {
            newLoginForm[mes] = event.target.value;
            setData({ loginForm: newLoginForm });
        };
    };
    const changeRemember = (event) => {
        const newLoginForm = data.loginForm;
        newLoginForm.rememberMe = event.target.checked;
        setData({ loginForm: newLoginForm });
    };
    const [setsnackbar] = React.useState({
        open: false,
        text: "",
    });

    React.useEffect(() => {
        if (getToken()) {
            console.log('bade')
            let history = createBrowserHistory();
            history.push({
                pathname: "/",
            });
            history.go();
        } else {
            getCode();
        }
    }, []);





    return (
        <div className={classes.root}>
            <Card className={classes.card}>
                <Container component="main" maxWidth="xs">
                    <CssBaseline />
                    <div className={classes.paper}>
                        {/* <Avatar className={classes.avatar}>
                    <LockOutlinedIcon />
                </Avatar> */}
                        <Typography component="h1" variant="h5">
                            若依欢迎您
                        </Typography>
                        {/* <form className={classes.form} noValidate> */}
                        <TextField
                            variant="outlined"
                            margin="normal"
                            required
                            fullWidth
                            id="email"
                            label="用户名"
                            name="email"
                            autoComplete="email"
                            autoFocus
                            value={data.loginForm.username}
                            onChange={changeForm("username")}
                        />
                        <TextField
                            variant="outlined"
                            margin="normal"
                            required
                            fullWidth
                            name="password"
                            label="密码"
                            type="password"
                            id="password"
                            autoComplete="current-password"
                            value={data.loginForm.password}
                            onChange={changeForm("password")}
                        />
                        <Grid container spacing={5}>
                            <Grid item xl>
                                <TextField
                                    variant="outlined"
                                    margin="normal"
                                    required
                                    fullWidth
                                    placeholder="验证码"
                                    onChange={changeForm("code")}
                                ></TextField>
                            </Grid>
                            <div style={{ width: '40px', height: '30px', marginTop: '35px' }}>
                                <img src={url} alt="" onClick={getCode} />
                            </div>

                        </Grid>

                        <FormControlLabel
                            control={<Checkbox value={data.loginForm.rememberMe} color="primary" />}
                            label="记住密码"
                            onChange={changeRemember}
                        />
                        <Button
                            type="submit"
                            fullWidth
                            variant="contained"
                            color="primary"
                            className={classes.submit}
                            onClick={handleLogin}
                        >
                            登录
                        </Button>
                        {/* <Button
                        type="submit"
                        fullWidth
                        variant="contained"
                        color="primary"
                        className={classes.submit}
                        onClick={handleClickRegister}
                    >
                        注册
                    </Button> */}
                        {/* <Grid container>
                                <Grid item xl >
                                    <Link href="/register" variant="body2">
                                        没有注册?去注册
                                    </Link>
                                </Grid>
                            </Grid> */}
                        {/* </form> */}
                    </div>
                    <Box mt={8}>
                        <Copyright />
                    </Box>
                </Container>
            </Card>
        </div>

    );
}